package com.leesche.zcsp.node.web.controller.web.v2.qrcode;

import com.leesche.zcsp.node.utils.FileToZipUtil;
import com.leesche.zcsp.node.utils.PropKit;
import com.leesche.zcsp.node.utils.QRCodeUtil;
import com.leesche.zcsp.node.utils.UtilDate;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.controller.web.v2.admin.WebAdminController;
import com.leesche.zcsp.node.web.model.PubDeviceShortCode;
import com.leesche.zcsp.node.web.service.PubDeviceShortCodeService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import static com.leesche.zcsp.node.utils.UUIDGenerateUtil.generateShortUuid;

/**
 * Created by kaider on 2017/1/19.
 */
@Controller
@RequestMapping("/v2/factory/qrcode")
public class WebFactoryQRCodeController extends WebAdminController {

    private final static Logger LOGGER = LoggerFactory.getLogger(WebFactoryQRCodeController.class);

    private final static String destPath = PropKit.use("rqcode.properties").get("destPath");
    private final static String payCodeProp = PropKit.use("rqcode.properties").get("payCode1");
    private static String zipFileName = UtilDate.getDate();

    @Autowired
    private PubDeviceShortCodeService codeService;

    /**
     * 生成二维码
     * @param codeNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/makeQRCode", method = RequestMethod.POST)
    public Map<String,Object> makeQRCode(
        Integer codeNum
    ){
        try {
            Long adminId = getFactoryAdminId();
            String userShortCode = getUserShortCode();
            if(StringUtils.isNotBlank(userShortCode)){
                makeZipFile(codeNum,adminId,userShortCode);
            }else{
                return WebResult.failure("没有用户简码").toMap();
            }
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 检查文件是否存在
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkFile", method = RequestMethod.GET)
    public Map<String, Object> checkFileIsNotNull(){
        try {
            zipFileName = UtilDate.getDate();
            Long adminId = getFactoryAdminId();
            File file = new File(destPath+adminId+"/device/"+zipFileName+"/"+zipFileName+".zip");
            if(file.exists()!=false){
                return WebResult.success().toMap();
            }else{
                return WebResult.failure("文件不存在").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 下载压缩包
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/downloadZip", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download() throws IOException {
        zipFileName = UtilDate.getDate();
        Long adminId = getFactoryAdminId();
        File file = new File(destPath+adminId+"/device/"+zipFileName+"/"+zipFileName+".zip");
        String filePathName = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");

        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        headers.setContentDispositionFormData("attachment", filePathName);

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    /**
     * 生成压缩二维码压缩文件
     * @param codeNum
     * @param adminId
     * @param userShortCode
     * @throws Exception
     */
    private void makeZipFile(int codeNum, Long adminId, String userShortCode) throws Exception{
        FileToZipUtil.deleteDirectory(destPath+adminId+"/device");
        zipFileName = UtilDate.getDate();
        for(int i=0;i<codeNum;i++){
            PubDeviceShortCode shortCode = new PubDeviceShortCode();
            shortCode.setPrefix(userShortCode);
            shortCode.setAdminid(adminId);
            shortCode.setShortcode(userShortCode+generateShortUuid());
            codeService.insert(shortCode);
            String deviceCode = userShortCode+shortCode.getShortcodeid();
            QRCodeUtil.encode(deviceCode,destPath+adminId+"/device/"+zipFileName,true, deviceCode);
            String payCode = "zf"+deviceCode;
            QRCodeUtil.encode(payCodeProp.replace("PAYCODE",payCode).toString(), destPath+adminId+"/device/"+zipFileName,true, payCode);
        }
        //打包成zip文件
        FileToZipUtil.makeZipFile(destPath+adminId+"/device/"+zipFileName,zipFileName);
    }

}
